﻿using System.Linq.Expressions;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using PoemGame.Domain.GameAggregate;

namespace PoemGame.Repository.MongoDb
{
    public class GameRepository:IGameRepository
    {
        /// <summary>
        /// 指定的表
        /// </summary>
        const string tbName = "game";

        private readonly IMongoDatabase database;

        public GameRepository(IMongoDatabase database)
        {
            this.database=database;
        }
        public async Task<Game?> GetAsync(Guid id)
        {
            IMongoCollection<Game> colTemp = 
                database.GetCollection<Game>(tbName);
            return await colTemp.Find(o => o.Id == id)
                .FirstOrDefaultAsync();
        }

        public async Task<Guid> AddAsync(Game game)
        {
            IMongoCollection<Game> colTemp = 
                database.GetCollection<Game>(tbName);

            await colTemp.InsertOneAsync(game);
            return game.Id;
        }

        public async Task UpdateAsync(Game game)
        {
            IMongoCollection<Game> colTemp = 
                database.GetCollection<Game>(tbName);
            await colTemp.ReplaceOneAsync<Game>(o => o.Id == game.Id, game);
        }

        public async Task RemoveAsync(Game game)
        {
            IMongoCollection<Game> colTemp = 
                database.GetCollection<Game>(tbName);
            await colTemp.DeleteOneAsync<Game>(o => o.Id == game.Id);
        }

        public async Task<IEnumerable<Game>> GetAllAsync()
        {
            IMongoCollection<Game> colTemp = 
                database.GetCollection<Game>(tbName);
            return await colTemp.AsQueryable<Game>().ToListAsync();
        }

        public async Task<IEnumerable<Game>> GetByConditionAsync(
            Expression<Func<Game, bool>> predicate)
        {
            IMongoCollection<Game> colTemp = 
                database.GetCollection<Game>(tbName);
            return await colTemp.AsQueryable<Game>()
                .Where(predicate).ToListAsync();
        }
    }
}
